<?php
/**
 * FileName: TraitValidation.php
 * Author: Fei.Song
 * Date: 2021/6/25 10:34
 * Created by PhpStorm
 * Desc:
 */

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Validator;

trait TraitValidation {
    protected $validator;
    protected $rules;
    protected $attributes;
    protected $messages;

    protected function validateRequest(Request $request, $name = null) {
        if (!$this->getValidator($name)) {
            return;
        }

        $this->validate($request, $this->rules, $this->messages, $this->attributes);
    }

    protected function validateData($input, $name = null) {
        if (!$this->getValidator($name)) {
            return;
        }

        $validator = Validator::make($input, $this->rules, $this->messages, $this->attributes);
        $validator->after(function ($validator) {
            $this->customValidate($validator);
        });
        return $validator->validate();

    }

    protected function getValidator($name = null) {

        list($controller, $method) = explode('@', Route::currentRouteAction());

        $method = $name ?: $method;

        $class = str_replace('Controller', 'Validation', $controller);

        if (!class_exists($class) || !method_exists($class, $method)) {
            return false;
        }

        $this->validator = new $class;
        $validation = $this->validator->$method();

        $this->rules = Arr::get($validation, 'rules', []);
        $this->attributes = Arr::get($validation, 'attributes', []);
        $this->messages = Arr::get($validation, 'messages', []);
        return $this->validator;
    }

    protected function customValidate(\Illuminate\Contracts\Validation\Validator $validator) {
        return $this->validator->customValidate($validator);
    }

}